from fastapi.exceptions import HTTPException
from sqlalchemy.orm import Session
from starlette import status
from . import models, schemas
import base64
import time
from datetime import timedelta, datetime
from typing import Optional
from common import jwt_utils, hash


# 创建用户
def create_user(db: Session, user: schemas.CreateUser):
    db_user = models.User(**user.dict())
    db_user.password = hash.get_password_hash(db_user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

# 根据用户名查询用户
def get_user_name(db: Session, username: str):
    return db.query(models.User).filter(models.User.username == username).first()

# 根据id查询用户
def get_user(db: Session, user_id: int):
    return db.query(models.User).filter(models.User.userID == user_id).first()

# 查询用户列表
def get_users(db: Session, skip: int= 0, limit: int = 10):
    return db.query(models.User).offset(skip).limit(limit).all()

# 更新用户
def update_user(db: Session, user: schemas.CreateUser):
    db_user = models.User(**user.dict())
    return

# 删除用户
def delete_user(db: Session, userid: int):
    return

# 用户登录
def user_login(db: Session, username: str, password: str):
    # user = models.User(**user.dict())
    db_user = db.query(models.User).filter(models.User.username == username).first()
    if db_user is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    if db_user.state == False:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户已锁定")
    if hash.verify_password(password, db_user.password) == False:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户密码不正确")
    access_token_expires = timedelta(minutes=jwt_utils.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = jwt_utils.created_access_token(
        data={"sub": db_user.username},
        expires_delta=access_token_expires
    )
    return access_token




